package com.travelsky.flash.util.msg;

import java.io.IOException;
import java.net.URI;

import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import org.apache.log4j.Logger;

/**
 * @Description 消息推送客户端
 * @author syuan
 * @date 2015年6月1日 下午5:34:35 Company: TravelSky
 */
@ClientEndpoint
public class WebSocketClient {

	private static Logger logger = Logger.getLogger(WebSocketClient.class);

	Session userSession = null;
	private MessageHandler messageHandler;

	public WebSocketClient(URI endpointURI) {
		WebSocketContainer container = ContainerProvider.getWebSocketContainer();
		try {
			container.connectToServer(this, endpointURI);
		} catch (Exception e) {
			logger.error("", e);
		}

	}

	@OnOpen
	public void onOpen(Session userSession) {
		logger.info("---------------opening websocket------------------");
		this.userSession = userSession;
	}

	@OnClose
	public void onClose(Session userSession, CloseReason reason) {
		logger.info("-----------------closing websocket------------");
		this.userSession = null;
	}

	@OnMessage
	public void onMessage(String message) {
		if (this.messageHandler != null) {
			this.messageHandler.handleMessage(message);
		}
	}

	public void addMessageHandler(MessageHandler msgHandler) {
		this.messageHandler = msgHandler;
	}

	public void sendMessage(String message) {
		try {
			this.userSession.getBasicRemote().sendText(message);
		} catch (IOException e) {
			logger.error("", e);
		}
	}

	public static interface MessageHandler {

		public void handleMessage(String message);
	}
}
